package com.zz.springboot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
public class ThreadPoolConfig {

    /**
     * Spring-ThreadPoolTaskExecutor
     * @return
     */
    @Bean("threadPoolTaskExecutor")
    public static ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setMaxPoolSize(10);
        threadPoolTaskExecutor.setCorePoolSize(5);
        threadPoolTaskExecutor.setThreadNamePrefix("async-parse-task-");
        threadPoolTaskExecutor.setQueueCapacity(200);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        /* 用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean */
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        /* 用来设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住 */
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60);
        /* 线程池初始化：最终底层还是要调用JDK的ThreadPoolExecutor进行实现 */
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
